package com.example.shop.fgo.ui.fragment;


import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.example.shop.fgo.Constant;
import com.example.shop.fgo.R;
import com.example.shop.fgo.base.YBaseFragment;
import com.example.shop.fgo.entity.FileListEntity;
import com.example.shop.fgo.entity.ShareEntity;
import com.example.shop.fgo.net.FileListServe;
import com.example.shop.fgo.net.ShareServe;
import com.example.shop.fgo.task.common.view.TaskingsActivity;
import com.example.shop.fgo.task.download.controller.DownloadController;
import com.example.shop.fgo.task.upload.view.SDScanActivity;
import com.example.shop.fgo.ui.adapter.ItemLvFileAdapter;
import com.example.shop.fgo.ui.dialog.DigCreateDir;
import com.example.shop.fgo.ui.dialog.DigSearch;
import com.example.shop.fgo.ui.dialog.DigSort;
import com.example.shop.fgo.ui.popwindow.PopMoreFragWp;
import com.example.shop.fgo.ui.views.PathNavi;
import com.example.shop.fgo.utils.CookieUtil;
import com.example.shop.library.net.NetJsonUtil;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class WPFragment extends YBaseFragment implements OnRefreshListener, OnLoadMoreListener, AdapterView.OnItemClickListener, View.OnClickListener {
    public SwipeToLoadLayout mLayoutRefresh;
    private ListView mSwipeTarget;
    private Map<String, Object> mMapRefreshParams = new HashMap<>();
    private Map<String, Object> mMapLoadMoreParams = new HashMap<>();
    //当前所处父目录ID---CID
    public  String mCidNow = "0";
    private RefreshCallback mRefreshCallback;
    public  List<FileListEntity.DataEntity> mDataEntitys;
    private LoadMoreCallback mLoadMoreCallback;
    public ItemLvFileAdapter mItemLvFileAdapter;

    public List<FileListEntity.PathEntity> mPathEntities;

    private int mLastCount;
    private int mCount;
    public PathNavi mPathNavi;


    private TextView mTvUploadBottomFragWp;
    private TextView mTvShareBottomFragWp;
    private TextView mTvDownloadBottomFragWp;
    private TextView mTvMoreBottomFragWp;
    private TextView mTvGoDowloadingList;



    private PopMoreFragWp mPopMoreFragWp;
    private DigCreateDir mDigCreateDir;
    private DigSearch mDigSearch;
    private DigSort mDigSort;

    private DownloadController mDownloadController;
    @Override
    public boolean isNeedTitle() {
        return false;
    }

    @Override
    protected void firstInit() {
        initRefreshParams();
        initLoadMoreParams();
        requestDir("0");
    }

    public WPFragment() {
        // Required empty public constructor
    }

    @Override
    public int setRootView() {
        return R.layout.fragment_wp;
    }

    @Override
    public void initViews() {

        mLayoutRefresh = (SwipeToLoadLayout) findViewById(R.id.layout_refresh);
        mSwipeTarget = (ListView) findViewById(R.id.swipe_target);
        mPathNavi = (PathNavi) findViewById(R.id.path_navi);
        mPathNavi.setOnNaviItemClickListener(new PathNavi.OnNaviItemClickListener() {
            @Override
            public void onItemClick(FileListEntity.PathEntity pathEntity) {
                requestDir(pathEntity.getCid());
            }
        });
        mLayoutRefresh.setOnRefreshListener(this);
        mLayoutRefresh.setOnLoadMoreListener(this);
        mSwipeTarget.setOnItemClickListener(this);

        mTvUploadBottomFragWp   = (TextView) findViewById(R.id.tv_upload_bottom_frag_wp);
        mTvShareBottomFragWp     = (TextView) findViewById(R.id.tv_share_bottom_frag_wp);
        mTvDownloadBottomFragWp  = (TextView) findViewById(R.id.tv_download_bottom_frag_wp);
        mTvMoreBottomFragWp        = (TextView) findViewById(R.id.tv_more_bottom_frag_wp);
        mPopMoreFragWp=new PopMoreFragWp(mActivitySelf);
        mDownloadController=new DownloadController();
        mPopMoreFragWp.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                changeMoreState();
            }
        });
        mPopMoreFragWp.setOnClickListener(this);
        mTvUploadBottomFragWp  .setOnClickListener(this);
        mTvShareBottomFragWp   .setOnClickListener(this);
        mTvDownloadBottomFragWp.setOnClickListener(this);
        mTvMoreBottomFragWp    .setOnClickListener(this);
        mTvGoDowloadingList = (TextView) findViewById(R.id.tv_go_dowloading_list);
        mTvGoDowloadingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TaskingsActivity.goToMe(mActivitySelf,TaskingsActivity.FROM_DOWN);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_more_bottom_frag_wp:
                    showMoreWindow();
                break;
            case R.id.tv_refresh_bottom_frag_wp:
                mLayoutRefresh.setRefreshing(true);
                break;
            case R.id.tv_share_bottom_frag_wp:
                doShare();
                break;
            case R.id.tv_dir_bottom_frag_wp:
                doCreateDir();
                break;
            case R.id.tv_search_bottom_frag_wp:
                doSearch();
                break;
            case R.id.tv_sort_bottom_frag_wp:
                doSort();
                break;
            case R.id.tv_download_bottom_frag_wp:
                doDownload();
                break;
            case R.id.tv_upload_bottom_frag_wp:
                doUpload();
                break;
        }
    }

    private void doUpload() {
        Bundle bundle=new Bundle();
        bundle.putString("cid",mCidNow);
        goToActivity(SDScanActivity.class,bundle);
    }

    private void doDownload() {
        mDownloadController.addTasksToQueue(mItemLvFileAdapter.mDataEntitiesChecked,mPathEntities);
        mTvGoDowloadingList.setVisibility(View.VISIBLE);
    }

    private void doSort() {
        if (mDigSort==null) {
            mDigSort = new DigSort(mActivitySelf,this);
        }
        mDigSort.show();
    }

    public void changeSortParams(String o,String asc){
        mMapRefreshParams.put("o",o);
        mMapRefreshParams.put("asc",asc);
        mMapLoadMoreParams.put("o",o);
        mMapLoadMoreParams.put("asc",asc);

        requestDir(mCidNow);
    }

    private void doSearch() {
        if (mDigSearch==null) {
            mDigSearch = new DigSearch(mActivitySelf,this);
        }
        mDigSearch.show();
    }
    private void doCreateDir() {
        if (mDigCreateDir==null) {
            mDigCreateDir = new DigCreateDir(mActivitySelf,this);
        }
        mDigCreateDir.show();
    }

    private void doShare() {
        ShareServe shareServe = NetJsonUtil.getRetrofit(Constant.BASE_URL, ShareServe.class);
        Map<String,Object> map=new HashMap<>();
        //Post fid=1232& count=0&time=2014-01-10
        if (mItemLvFileAdapter.mDataEntitiesChecked.size()==0) {
            Toast.makeText(mActivitySelf, "请至少选择一个要分享的文件", Toast.LENGTH_SHORT).show();
            return;
        }if (mItemLvFileAdapter.mDataEntitiesChecked.size() > 1){
            Toast.makeText(mActivitySelf, "只能一次分享一个文件", Toast.LENGTH_SHORT).show();
            return;
        }
        map.put("fid",mItemLvFileAdapter.mDataEntitiesChecked.get(0).getFid());
        map.put("count",666);
        map.put("time","2022-01-01");
        Call<ShareEntity> shareEntityCall = shareServe.requestWL(map, CookieUtil.getCookie());
        shareEntityCall.enqueue(new Callback<ShareEntity>() {
            @Override
            public void onResponse(Call<ShareEntity> call, Response<ShareEntity> response) {
                ShareEntity shareEntity = response.body();
                shareEntity.setLink(shareEntity.getLink().replace("http://fyimail.vicp.net:1080", "http://101.200.183.103:9999"));

                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();
                // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
                oks.setTitle("Fatego资源");
                // text是分享文本，所有平台都需要这个字段
                oks.setText("好东西要一起分享：" + shareEntity.getLink());

// 启动分享GUI
                oks.show(mActivitySelf);
            }

            @Override
            public void onFailure(Call<ShareEntity> call, Throwable t) {

            }
        });
            }




    private void showMoreWindow() {
        mPopMoreFragWp.showAsDropDown(mTvMoreBottomFragWp);
        changeMoreState();
    }

    private boolean IsMoreSelected;
    private Drawable mMoreNormal,mMoreSelected;
    private void changeMoreState() {
        if (mMoreNormal==null) {
            mMoreNormal=this.getResources().getDrawable(R.drawable.menu_more_gray);
            mMoreSelected=this.getResources().getDrawable(R.drawable.menu_more_selected_gray);

            Rect rect=new Rect(0,0,mMoreNormal.getIntrinsicWidth(),mMoreNormal.getIntrinsicHeight());
            mMoreNormal.setBounds(rect);
            mMoreSelected.setBounds(rect);
        }
        if (IsMoreSelected) {
            mTvMoreBottomFragWp.setCompoundDrawables(null,mMoreNormal,null,null);
            mTvMoreBottomFragWp.setTextColor(Color.BLUE);
        }else{
            mTvMoreBottomFragWp.setCompoundDrawables(null,mMoreSelected,null,null);
            mTvMoreBottomFragWp.setTextColor(Color.BLACK);
        }
        IsMoreSelected=!IsMoreSelected;
    }

    @Override
    public void initDatas() {
       initRefreshParams();
       initLoadMoreParams();
       requestDir("0");
    }

    private void initLoadMoreParams() {
        mMapLoadMoreParams.put("ct","list");
        mMapLoadMoreParams.put("aid","1");
        mMapLoadMoreParams.put("o","user_ptime");
        mMapLoadMoreParams.put("asc","0");
        mMapLoadMoreParams.put("offset","0");
        mMapLoadMoreParams.put("limit","240");
    }

    private void initRefreshParams() {
         /*ct=list为显示用户的文件列表
            aid=1为普通文件，默认为1
            cid=0为父目录id , 默认为0
            o=user_ptime 为排序方法
            asc=0 0为顺序排列，1为倒序排列
            offset=0 为从记录的第几条开始
            limit=28 为每页显示数目
        * */
        mMapRefreshParams.put("ct","list");
        mMapRefreshParams.put("aid","1");
        mMapRefreshParams.put("o","user_ptime");
        mMapRefreshParams.put("asc","0");
        mMapRefreshParams.put("offset","0");
        mMapRefreshParams.put("limit","60");
    }
    /**
     *
     * @param cidDes
     */
    private void requestDir(String cidDes) {
        mCidNow=cidDes;
        mMapRefreshParams.put("cid",mCidNow);
        //一上来使网盘界面处于刷新态。
        mLayoutRefresh.setRefreshing(true);
    }

    @Override
    public void onRefresh() {
        doNetRefresh();

    }

    private void doNetRefresh() {
        FileListServe fileListServe = NetJsonUtil.getRetrofit(Constant.BASE_URL, FileListServe.class);
        Call<FileListEntity> fileListEntityCall = fileListServe.requestFiles(mMapRefreshParams, CookieUtil.getCookie());
        if (mRefreshCallback==null) {
            mRefreshCallback=new RefreshCallback();
        }
        fileListEntityCall.enqueue(mRefreshCallback);

    }
    private void doNetLoadMore(String cidDes,int offset){
        mMapLoadMoreParams.put("cid",cidDes);
        mMapLoadMoreParams.put("offset",offset);
        FileListServe fileListServe=NetJsonUtil.getRetrofit(Constant.BASE_URL,FileListServe.class);
        Call<FileListEntity> call=fileListServe.requestFiles(mMapLoadMoreParams, CookieUtil.getCookie());
        if (mLoadMoreCallback==null) {
            mLoadMoreCallback=new LoadMoreCallback();
        }
        call.enqueue(mLoadMoreCallback);
    }
    @Override
    public void onLoadMore() {
        if(hasMoreDatas()){
            doNetLoadMore(mCidNow,mSwipeTarget.getCount());
        }else{
            Toast.makeText(mActivitySelf, "没有更多数据了", Toast.LENGTH_SHORT).show();
            mLayoutRefresh.setRefreshing(false);
        }
    }

    private boolean hasMoreDatas() {
        Logger.e(mSwipeTarget.getCount()+"");
        Logger.e(mCount+"");
        if (mSwipeTarget.getCount()>=mCount) {
            return false;
        }
        return true;
    }
    /*
    * 1.处理当前Fragment的back 动作
    * 2、返回Boolean 来判断当前Fragment是否还要处理back动作
    * */
    public boolean wpFragBack(){
        if (mPathEntities.size()<=1) {
            return false;//<=1 证明是最里层的文件/夹
        }
        //回退
        requestDir(mPathEntities.get(mPathEntities.size()-2).getCid());
        return true;
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileListEntity.DataEntity dataEntity = mDataEntitys.get(position);
        String cid = dataEntity.getCid();
        if (TextUtils.isEmpty(cid)){
            Toast.makeText(mActivitySelf, "点到了文件", Toast.LENGTH_SHORT).show();
        }else {
            requestDir(cid);
        }
    }




    //刷新的回调
    private class RefreshCallback implements Callback<FileListEntity>{



        @Override
        public void onResponse(Call<FileListEntity> call, Response<FileListEntity> response) {
            FileListEntity fileListEntity = response.body();
            mCount=fileListEntity.getCount();
            mDataEntitys = fileListEntity.getData();
            if (mItemLvFileAdapter==null) {
                mItemLvFileAdapter=new ItemLvFileAdapter(mActivitySelf,mDataEntitys);
                mSwipeTarget.setAdapter(mItemLvFileAdapter);
            }else{
                mItemLvFileAdapter.setEntities(mDataEntitys);
            }
            //一旦刷新完毕，终止刷新
            mLayoutRefresh.setRefreshing(false);
            mLastCount=mDataEntitys.size();
            mPathEntities = fileListEntity.getPath();
            Logger.e(mPathEntities.toString());
            mPathNavi.setPathEntities(mPathEntities);

        }

        @Override
        public void onFailure(Call<FileListEntity> call, Throwable t) {
            mLayoutRefresh.setRefreshing(false);
        }
    }
   //加载更多的回调
    private class  LoadMoreCallback implements Callback<FileListEntity>{

        @Override
        public void onResponse(Call<FileListEntity> call, Response<FileListEntity> response) {
            FileListEntity fileListEntity = response.body();
            List<FileListEntity.DataEntity> data = fileListEntity.getData();
            mItemLvFileAdapter.addDatas(data);


            mLayoutRefresh.setLoadingMore(false);



            if (mDataEntitys.size()==mLastCount) {
                Toast.makeText(mActivitySelf, "没有更多的数据了", Toast.LENGTH_SHORT).show();
                mLayoutRefresh.setLoadingMore(false);
            }
            mLastCount=mDataEntitys.size();
        }

        @Override
        public void onFailure(Call<FileListEntity> call, Throwable t) {
            mLayoutRefresh.setLoadingMore(false);
        }
    }
}
